<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-form">
      <div class="form-content">
        <div class="left">
          <el-input
            v-model="queryParams.flowName"
            placeholder="搜索流程名称..."
            class="search-input"
            :prefix-icon="Search"
            clearable
            @keyup.enter="handleQuery"
          />
          <el-button-group class="btn-group">
            <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
          </el-button-group>
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <base-table
      :data="tableData"
      :loading="loading"
      :total="total"
      v-model:pagination="queryParams"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <el-table-column type="index" width="60" align="center">
        <template #default="scope">
          <span class="index-cell">{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="name" label="流程名称" min-width="200" align="center">
        <template #default="{ row }">
          <div class="name-cell">
            <el-icon><Document /></el-icon>
            <el-button link type="primary" @click="toFlowDetail(row)">
              {{ row.name }}
            </el-button>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="创建时间" align="center" width="180">
        <template #default="{ row }">
          <span class="time-text">{{ row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态" align="center" width="100">
        <template #default="{ row }">
          <el-tag
            :type="getStatusType(row.status)"
            effect="light"
            class="status-tag"
            round
          >
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="remark" label="说明" align="center" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="remark-text">{{ row.remark || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="{ row }">
          <div class="action-group">
            <el-tooltip content="发起流程" placement="top">
              <el-button link type="success" :icon="VideoPlay" @click="startFlow(row.id)" />
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary" :icon="Edit" @click="toFlowDetail(row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" :icon="Delete" @click="handleDelete(row)" />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </base-table>

    <PreviewForm
      :visible="previewVisible"
      :flow-id="flowId"
      @cancel="previewVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Search, 
  Refresh, 
  Plus, 
  Edit, 
  Delete, 
  VideoPlay,
  Document,
  InfoFilled
} from '@element-plus/icons-vue';
import { getFlowData, getFlowDataInfo } from "../../../api/flow.js";
import PreviewForm from "../preview-form.vue";
import BaseTable from '@/components/Table/index.vue';

const store = useStore();
const router = useRouter();

// 数据定义
const loading = ref(false);
const tableData = ref([]);
const total = ref(0);
const previewVisible = ref(false);
const flowId = ref("");
const queryParams = reactive({
  page: 1,
  limit: 10,
  flowName: undefined,
});

// 获取数据
const getList = async () => {
  try {
    loading.value = true;
    const res = await getFlowData(queryParams);
    if (res.status === 0) {
      tableData.value = res.data.rows;
      total.value = res.data.total;
    }
  } catch (error) {
    console.error('获取流程列表失败:', error);
    ElMessage.error('获取流程列表失败');
  } finally {
    loading.value = false;
  }
};

// 查询操作
const handleQuery = () => {
  queryParams.page = 1;
  getList();
};

const resetQuery = () => {
  queryParams.flowName = undefined;
  handleQuery();
};

// 分页操作
const handleSizeChange = (val) => {
  queryParams.limit = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.page = val;
  getList();
};

// 流程操作
const handleAdd = () => {
  router.push("/flowAdd");
};

const toFlowDetail = (row) => {
  router.push(`/flowEdit?id=${row.id}`);
};

const startFlow = async (id) => {
  try {
    const res = await getFlowDataInfo({ id });
    if (res.status === '0') {
      store.dispatch("form/updateConfig", JSON.parse(res.data.formData));
      flowId.value = res.data.processDefId;
      previewVisible.value = true;
    }
  } catch (error) {
    console.error('获取流程详情失败:', error);
    ElMessage.error('获取流程详情失败');
  }
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除流程 "${row.name}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 这里添加删除接口调用
    ElMessage.success('删除成功');
    getList();
  }).catch(() => {});
};

// 状态处理
const getStatusType = (status) => {
  const statusMap = {
    '0': 'info',
    '1': 'success',
    '2': 'warning',
    '3': 'danger'
  };
  return statusMap[status] || 'info';
};

const getStatusText = (status) => {
  const statusMap = {
    '0': '草稿',
    '1': '已发布',
    '2': '已停用',
    '3': '已作废'
  };
  return statusMap[status] || '未知';
};

// 添加行样式方法
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 24px;
  background-color: var(--el-bg-color-page);

  .search-form {
    padding: 16px 20px;
    background: var(--el-bg-color);
    border-radius: 8px;
    margin-bottom: 16px;
    border: 1px solid var(--el-border-color-lighter);

    .form-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left {
        display: flex;
        gap: 12px;
        align-items: center;

        .search-input {
          width: 300px;
          
          :deep(.el-input__wrapper) {
            &:hover {
              box-shadow: 0 0 0 1px var(--el-color-primary) inset;
            }
          }
        }

        .btn-group {
          .el-button {
            padding: 8px 16px;
          }
        }
      }

      .add-btn {
        padding: 8px 16px;
        
        .el-icon {
          margin-right: 4px;
        }
      }
    }
  }

  .table-card {
    background: var(--el-bg-color);
    border-radius: 8px;
    padding: 20px;
    border: 1px solid var(--el-border-color-lighter);

    :deep(.el-table) {
      .index-cell {
        display: inline-block;
        width: 24px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        color: var(--el-text-color-secondary);
        font-size: 13px;
      }

      .name-cell {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        
        .el-icon {
          font-size: 16px;
          color: var(--el-text-color-secondary);
        }
      }

      .time-text {
        color: var(--el-text-color-secondary);
        font-size: 13px;
      }

      .status-tag {
        padding: 0 12px;
        height: 22px;
      }

      .remark-text {
        color: var(--el-text-color-regular);
        font-size: 13px;
      }

      .action-group {
        display: flex;
        justify-content: center;
        gap: 16px;

        .el-button {
          font-size: 16px;
        }
      }

      td {
        padding: 16px 0;
        border-bottom: 1px solid var(--el-border-color-lighter);
      }

      tr:last-child td {
        border-bottom: none;
      }
    }

    .pagination-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid var(--el-border-color-lighter);

      .total-text {
        color: var(--el-text-color-secondary);
        font-size: 13px;
      }
    }
  }
}

// 暗黑模式适配
html.dark {
  .app-container {
    .search-form,
    .table-card {
      background: var(--el-bg-color);
      border-color: var(--el-border-color-darker);
    }
  }
}
</style>